//
//  WJMySigntruesViewController.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/29.
//

import UIKit

class WJMySigntruesViewController: WJBaseViewViewController {
    
    private var signatures: [WJSignatureHistoryModel] = []
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        let width = (view.bounds.width - 35) / 2
        let height = width + 40 // 图片高度+文字高度
        layout.itemSize = CGSize(width: width, height: height)
        layout.minimumInteritemSpacing = 11
        layout.minimumLineSpacing = 11
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .clear
        cv.register(WJMySigntruesCell.self, forCellWithReuseIdentifier: "WJMySigntruesCell")
        cv.dataSource = self
        cv.delegate = self

        return cv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "My Sign"
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(10)
        }
        
        loadLocalSignatures()
//        setRightNavigationBar()
    }
    
    func setRightNavigationBar() {
        let barButtonItem = UIBarButtonItem(
            image: UIImage(named: "vip_icon")?.withRenderingMode(.alwaysOriginal),
            style: .plain,
            target: self,
            action: #selector(clickVipAction(_:))
        )
        self.navigationItem.rightBarButtonItem = barButtonItem
    }
    
    @objc func clickVipAction(_ item: UIBarButtonItem) {
        let vc = RemoteConfigValues.getCurrentPurchaseVC()
        let nav = WJNavigationController(rootViewController: vc)
        nav.modalPresentationStyle = .fullScreen
        nav.modalTransitionStyle = .crossDissolve
        self.present(nav, animated: true)
    }
    
    private func loadLocalSignatures() {
        do {
            self.signatures = try WJSignatureHistoryModel.findAllTyped().sorted(by: { model1, model2 in
                model1.createdDate > model2.createdDate
            })
            if signatures.isEmpty {
                wjUpdateState(.noData)
            } else {
                wjUpdateState(.finished)
            }
            self.collectionView.reloadData()
        } catch {
            print("加载签名数据失败: \(error)")
        }
    }
    
    private func deleteModel(_ historyModel: WJSignatureHistoryModel) {
      
        let success = (try? historyModel.delete()) ?? false
        if success {
            signatures.removeAll(where: { $0.id == historyModel.id })
            if signatures.isEmpty {
                wjUpdateState(.noData)
            } else {
                wjUpdateState(.finished)
            }
            collectionView.reloadData()
        }
    }
}

// MARK: - 集合视图数据源和代理
extension WJMySigntruesViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return signatures.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WJMySigntruesCell", for: indexPath) as! WJMySigntruesCell
        let historyModel = signatures[indexPath.item]
        cell.configure(with: historyModel)
        cell.deleteClosure = { [weak self] in
            guard let self = self else { return }
            self.deleteModel(historyModel)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}

extension WJMySigntruesViewController: WJNoDataProtocol {
    var wjStateContainer: UIView {
        return self.collectionView
    }
    
    func wjFrame(for state: WJState) -> CGRect? {
        switch state {
        case .noData:
            return CGRect(x: 0, y: 248, width: view.bounds.width, height: 300)
        default:
            return nil
        }
    }
    
    func wjImage(for state: WJState) -> UIImage? {
        switch state {
        case .noData:
            return UIImage(named: "no_signed_image")
        default:
            return nil
        }
    }
    
    func wjButtonTitle(for state: WJState) -> String? {
        return nil
    }
    
    func wjTitle(for state: WJState) -> String {
        switch state {
        case .noData:
            return "No sign here yet."
        default:
            return ""
        }
    }
    
    func wjMessage(for state: WJState) -> String {
        return ""
    }
    
    func wjDidTapStateButton() {
        
    }
}
